package cn.admin.configcenter.configservice.util;

public class ConfigKey {

    public static String getKey(String dataId,String group) {
        StringBuilder sb = new StringBuilder();
        urlEncode(dataId,sb);
        sb.append('+');
        urlEncode(group,sb);
        return sb.toString();
    }

    private static void urlEncode(String str,StringBuilder sb) {

        for(int idx = 0; idx < str.length(); ++idx) {
            char c = str.charAt(idx);
            if ('+' == c) {
                sb.append("%2B");
            } else if ('%' == c) {
                sb.append("%25");
            } else {
                sb.append(c);
            }
        }
    }

    public static String[] parseKey(String groupKey) {
        StringBuilder sb = new StringBuilder();
        String dataId = null;
        String group;

        for(int i = 0; i < groupKey.length(); ++i) {
            char c = groupKey.charAt(i);
            if ('+' == c) {
                if (null != dataId) {
                    throw new IllegalArgumentException("invalid groupkey:" + groupKey);
                }

                dataId = sb.toString();
                sb.setLength(0);
            } else if ('%' == c) {
                ++i;
                char next = groupKey.charAt(i);
                ++i;
                char nextnext = groupKey.charAt(i);
                if ('2' == next && 'B' == nextnext) {
                    sb.append('+');
                } else {
                    if ('2' != next || '5' != nextnext) {
                        throw new IllegalArgumentException("invalid groupkey:" + groupKey);
                    }

                    sb.append('%');
                }
            } else {
                sb.append(c);
            }
        }

        group = sb.toString();
        if (group.length() == 0) {
            throw new IllegalArgumentException("invalid groupkey:" + groupKey);
        } else {
            return new String[]{dataId, group};
        }
    }

}
